package com.opencloud.iot.provider.controller;

import cn.hutool.core.date.DateUtil;
import com.opencloud.common.model.ResultBody;
import com.opencloud.iot.client.model.entity.*;
import com.opencloud.iot.provider.service.*;
import com.opencloud.iot.provider.service.feign.YwtRemoteService;
import com.opencloud.ywt.client.model.entity.BhyfStudent;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 物联网设备 信息统计
 * @author yeyong
 */
@Slf4j
@RestController
@Api(value = "物联网设备", tags = "物联网设备 信息统计")
public class IotDayMoveResultController {
    @Autowired
    private IotDayMoveResultService iotDayMoveResultService;

    @Autowired
    private IotNStrengService iotNStrengService;

    @Autowired
    private YwtRemoteService ywtRemoteService;

    @Autowired
    private IotTaskService iotTaskService;

    @Autowired
    private IotTaskRunService iotTaskRunService;
    /**
     * 获取日运动统计信息
     * @param watchmac
     * @param thisdate
     * @return
     */
    @ApiOperation(value = "获取日运动统计信息", notes = "获取日运动统计信息")
    @GetMapping(value = "/iot/daymovelist")
    public List<IotDayMoveResult> getIotDayMoveResult(
           @RequestParam(value = "watchmac",required = false)  String watchmac,
           @RequestParam(value = "thisdate",required = false) String thisdate
    )
    {
        return iotDayMoveResultService.findListPage(watchmac,thisdate);
    }

    /**
     * 创建日运动统计信息
     * @param watchmac
     * @param thisDate
     * @return
     */
    @ApiOperation(value = "创建日运动统计信息", notes = "创建日运动统计信息")
    @GetMapping(value = "/iot/daymovecreate")
    public ResultBody<Integer> CreateIotDayMoveResult(String watchmac,String thisDate){
        //执行任务
        if (watchmac!=null && thisDate!=null) {
            IotDayMoveResult model = DoCreate(watchmac, thisDate);
            return ResultBody.ok().data(model.getId());
        } else {
            List<IotTask> iotTaskList = iotTaskService.findTaskByType(2);
            for (int i = 0; i < iotTaskList.size(); i++) {
                IotTask task = iotTaskList.get(i);
                List<BhyfStudent> s = ywtRemoteService.getBhyfStudentList(task.getGid(),0);
                MyThread thisThread = new MyThread(task,s);
                thisThread.start();
            }
        }

        return ResultBody.ok().data(0);
    }


    public class MyThread extends Thread {
        IotTask t = new IotTask();//定义线程内变量
        List<BhyfStudent> students = new ArrayList<>();
        public MyThread(IotTask t,List<BhyfStudent> students) {
            //定义带参数的构造函数,达到初始化线程内变量的值
            this.t = t;
            this.students = students;
        }
        @Override
        public void run() {
            //生成新的任务执行
            Date dt1 = new Date();
            String startTime = DateUtil.formatDate(dt1)+" "+t.getStarttime().toString()+":00";
            String endTime = DateUtil.formatDate(dt1)+" "+t.getEndtime().toString()+":00";
            Date dtS = DateUtil.parseDateTime(startTime);
            Date dtE = DateUtil.parseDateTime(endTime);

            if (dt1.getTime() < dtS.getTime() || dt1.getTime() > dtE.getTime()) {
                //超出任务指定的时间点
                log.error("每日运动服务 超出任务指定的时间点");
            } else {
                System.out.println("开始执行任务");
                IotTaskRun entiy = new IotTaskRun();
                entiy.setCreatetime(new Date());
                entiy.setTaskid(t.getId());
                entiy.setThisdate(new Date());
                entiy.setException("");
                //开始执行任务
                int j =0;
                for (int i=0;i<students.size();i++)
                {
                    IotDayMoveResult bResult = DoCreate(students.get(i).getMac(),DateUtil.format(dt1, "yyyy-MM-dd"));
                    if(bResult!=null){j++;}
                }
                entiy.setResult("任务执行结束 学生数量："+students.size()+" 执行数量:"+j);
                entiy.setStatus(1);
                iotTaskRunService.AddTaskRun(entiy);
                log.error("任务执行结束 学生数量："+students.size()+" 执行数量:"+j);
            }
        }
    }

    public IotDayMoveResult DoCreate(String watchmac,String thisDate)
    {
        IotDayMoveResult entiy = new IotDayMoveResult();
        Long move1StartTime = DateUtil.parse(thisDate +" 08:00:00","yyyy-MM-dd HH:mm:ss").getTime()/1000;
        Long move1EndTime = DateUtil.parse(thisDate+" 12:00:00","yyyy-MM-dd HH:mm:ss").getTime()/1000;
        Long move2StartTime = DateUtil.parse(thisDate +" 15:00:00","yyyy-MM-dd HH:mm:ss").getTime()/1000;
        Long move2EndTime = DateUtil.parse(thisDate+" 16:30:00","yyyy-MM-dd HH:mm:ss").getTime()/1000;
        boolean isExistData = false;
        //2、查询当日该手环是否有数据
        List<IotDayMoveResult> iotDayMoveResults = new ArrayList<>();
            iotDayMoveResults = iotDayMoveResultService.findListPage(watchmac,thisDate);

        if (iotDayMoveResults!=null && !iotDayMoveResults.isEmpty()) {
            isExistData = true;
            entiy = iotDayMoveResults.get(0);
        }
        //5、按规则计算
        List<IotNStreng> nStrengs = new ArrayList<>();
        nStrengs = iotNStrengService.findList(move1StartTime+28800,move1EndTime+28800,watchmac);
        List<IotNStreng> nStrengs2 = new ArrayList<>();
        nStrengs2 = iotNStrengService.findList(move2StartTime+28800,move2EndTime+28800,watchmac);
        nStrengs.addAll(nStrengs2);
        if(nStrengs!=null && !nStrengs.isEmpty()) {
            //计算各种数据
            if (nStrengs.stream().filter((IotNStreng iots) -> iots.getStreng() >= 10).collect(Collectors.toList()).size() >= 300) {
                entiy.setWatchstatus(1);
            } else {
                entiy.setWatchstatus(0);
            }
            double high = nStrengs.stream().filter(s -> s.getStreng() > 150).count();
            double middle = nStrengs.stream().filter(s -> s.getStreng() <= 150 && s.getStreng() > 60).count();
            double low = nStrengs.stream().filter(s -> s.getStreng() <= 60).count();
            entiy.setWatchmac(watchmac);
            entiy.setThisdate(DateUtil.parseDate(thisDate));
            entiy.setHightimes(high * 10);
            entiy.setMiddletimes(middle * 10);
            entiy.setLowtimes(low * 10);
            entiy.setMovestatus(0);
            entiy.setMoveresult("");
            entiy.setThisdate(DateUtil.parseDate(thisDate));
            entiy.setUpdatetime(new Date());
            //3、有数据 更新 //4、无数据 插入
            if (!isExistData) {
                entiy.setCreatetime(new Date());
                iotDayMoveResultService.addIotDayMoveResult(entiy);
            } else {
                iotDayMoveResultService.updateIotDayMoveResult(entiy);
            }
        }
        return entiy;
    }
}
